﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using UnityScriptEngine;

namespace MBBHotelReservation
{
    public partial class frmRateManager : Form
    {
        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();

        DataTable items = new DataTable();
        DataTable roomRate = new DataTable();
        DataTable functionRate = new DataTable();

        string wrnEntMsg = "";

        bool addNew = false, Committing = false,
            isViewing = false;
        UnityElement curData;
        //AutoChecker
        Timer tmr = new Timer();
        int curEdit = -1;

        public frmRateManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        private void InitializeForm()
        {
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            //Start AutoCheck timer
            btnAdd.LostFocus += new EventHandler(delegate(object sender, EventArgs e)
            {
            //    txtName.Focus();
            });
            btnAdd.Click += new EventHandler(btnAdd_Click);
           
           
            btnSave.Visible = false;
            btnAdd.Visible = false;
            btnCancel.Visible = false;
            btnCancel.Click += new EventHandler(btnCancel_Click);
            grdItems.DoubleClick += new EventHandler(grdItems_DoubleClick);
            pnlForm.Enabled = false;
            btnSave.Click +=new EventHandler(btnSave_Click);
            txtType.SelectedIndexChanged += new EventHandler(txtType_SelectedIndexChanged);
            txtType.SelectedIndex = 0;
            LoadRates();
        }

        void txtType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtType.Text.Equals("Room"))
            {
                grdItems.DataSource = roomRate;
                groupState(true);
            }
            else
            {
                grdItems.DataSource = functionRate;
                groupState(false);
            }
        }


        void btnCancel_Click(object sender, EventArgs e)
        {
            addNew = false;
            clearInfo();
            txtType.SelectedIndex = 0;
            btnAdd.Visible = false;
            btnSave.Visible = false;
            btnCancel.Visible = false;
            
        }

        void grdItems_DoubleClick(object sender, EventArgs e)
        {
            curEdit = grdItems.SelectedRows[0].Index;
            if (!txtType.Text.Equals("Room"))
            {
                dat[1].Data_Get(curEdit, out curData);

                txtHall.Text = curData.Data_GetField(0).ToString();
                txtRate.Value = decimal.Parse(curData.Data_GetField(1).ToString());
                txtAdditionalRate.Value = decimal.Parse(curData.Data_GetField(2).ToString());
            }
            else
            {
                dat[0].Data_Get(curEdit, out curData);

                txtRoom.Text = curData.Data_GetField(1).ToString();
                dayRate.Value = decimal.Parse(curData.Data_GetField(2).ToString());
                overnightRate.Value = decimal.Parse(curData.Data_GetField(3).ToString());
                OneDayRate.Value = decimal.Parse(curData.Data_GetField(4).ToString());
            }
            btnAdd.Visible = false;
            btnSave.Visible = true;
            btnCancel.Visible = true;
            
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            Committing = true;
            addNew = false;
            States(false);
            Commit();
        }

        void btnAdd_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Please double check your entries before committing.\r\n" +
                "Do you wish to continue saving?", "Commit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlg == System.Windows.Forms.DialogResult.No) return;
            Committing = true;
            addNew = true;
            States(false);
            Commit();
        }

        //Process Ended
        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                
                MessageBox.Show(desc);
                States(true);
                switch (id)
                {
                    case "COMMIT":
                        Committing = false;
                        break;
                }
                tmr.Enabled = true;
            });
        }
        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "COMMIT":
                        LoadRates();
                        break;
                    case "LOADRATES":
                        proc.DBPUX_Data_Fetch(out dat);
                        roomRate = dat[0].ToDataTable();
                        functionRate = dat[1].ToDataTable();

                        if (txtType.Text.Equals("Room"))
                        {
                            grdItems.DataSource = roomRate;
                            groupState(true);
                        }
                        else
                        {
                            grdItems.DataSource = functionRate;
                            groupState(false);
                        }

                        States(true);
                        btnSave.Visible = false;
                        btnCancel.Visible = false;
                        break;
                    
                    
                    case "LOAD":
                        proc.DBPUX_Data_Fetch(out dat);
                        lblWarningEntry.Text = "Loaded @ " + proc.ProcEnd() + " sec.";
                        break;
                };
               
                
            });
        }
        

        //Operations
        void groupState(bool state)
        {
            room.Visible = state;
            function.Visible = !state;
            clearInfo();
        }
        void clearInfo()
        {
            txtAdditionalRate.Value = 0;
            txtRate.Value = 0;
            txtHall.Text = "";

            txtRoom.Text = "";
            OneDayRate.Value = 0;
            overnightRate.Value = 0;
            dayRate.Value = 0;
        }
        void Commit()
        {
            UnityScript u = new UnityScript("COMMIT", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            //Construct Expenses Items
            if (addNew)
            {
                u.Script_Add(Script.DBPUX_INSERT, "tblamenitieslookup(fCategory,fName, fPrice)",
                    new string[]{
                        txtType.Text,
                        //txtName.Text,
                        //txtPrice.Text
                    });
            }
            else
            {
                if(txtType.Text.Equals("Room"))
                {
                    u.Script_Add(Script.DBPUX_UPDATE, string.Format("tblroomlookup SET " +
                        "fRoomNumber = '{0}', fDayRate='{1}', fNightRate='{2}', f24HoursRate='{3}'", txtRoom.Text, float.Parse(dayRate.Value.ToString()).ToString(), overnightRate.Value.ToString(), OneDayRate.Value.ToString()),
                        string.Format("(fID='{0}') AND (fStamp='{1}')", curData.Data_ID.ToString(), curData.Data_Stamp));
                }
                else
                {
                     u.Script_Add(Script.DBPUX_UPDATE, string.Format("tblfunctionlookup SET " +
                        "fFunctionHall = '{0}', fRate='{1}', fAdditionalrate='{2}'", txtHall.Text, float.Parse(txtRate.Value.ToString()).ToString() , txtAdditionalRate.Value.ToString()),
                        string.Format("(fID='{0}') AND (fStamp='{1}')", curData.Data_ID.ToString(), curData.Data_Stamp));
                }
            }
            
            //Transaction Log
            //u.Script_Add(Script.DBPUX_INSERT, "tblpurchaseorderlog(fUser, fMsg, fDate)",
            //    new string[]{
                    //StoreClientModule.Common.Username,
            //        "Added " + txtPONum.Text + " worth " + gtotal.ToString("#,#0.00"),
            //        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
           //     });
            u.Script_Add(Script.DBPUX_COMMIT);
            //Wait if UnityCall is in progress.
            System.Threading.Thread.Sleep(10);
            while (proc.IsRunning)
            {

            }
            proc.Run(u);
        }
        void States(bool s)
        {
            grpDetails.Enabled = s;
            grdItems.Enabled = s;
        }
        //This will load rates
        void LoadRates()
        {
            UnityScript u = new UnityScript("LOADRATES", 5);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fBuildingName AS 'Building', fRoomNumber AS 'Room Number', fDayRate AS 'Day Rate', fNightRate AS 'Overnight Rate', f24HoursRate AS 'One Day Rate', fStamp FROM tblroomlookup");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fFunctionHall AS 'Function Hall', fRate AS 'Rate', fAdditionalRate AS 'Additional', fStamp FROM tblfunctionlookup");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        void LoadFood()
        {
            UnityScript u = new UnityScript("LOADFOOD", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fCategory AS 'Category', fName AS 'Name', fPrice AS 'Price', fStamp FROM tblamenitieslookup");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }

        void FormatTable()
        {
            for (int i = 0; i < grdItems.Rows.Count; i++)
            {
                string value = grdItems.Rows[i].Cells[2].Value.ToString();
                grdItems.Rows[i].Cells[2].Value = float.Parse(value).ToString("#,#0.00");
            }
        }
        //Printing Module
        
    }
    //Code Log:
    //- Speed up entry checking by removing the method call from the timer.
    //- Removed the CheckContent method as the CheckEntry method is sufficient for checking
    //  user inputs.
}